import React, { useState } from 'react';
import { 
  Table, 
  Input, 
  Select, 
  Button, 
  DatePicker, 
  Modal, 
  Form, 
  message, 
  Popconfirm,
  Tag,
  Space
} from 'antd';
import { 
  PlusOutlined, 
  ExportOutlined, 
  ImportOutlined,
  SearchOutlined,
  ReloadOutlined
} from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import  './emergencyResponse.less';

const { RangePicker } = DatePicker;
const { TextArea } = Input;

interface DataType {
  key: number;
  sequence: number;
  level: string;
  responseName: string;
  responseContent: string;
  time: string;
  initiator: string;
  status: 'active' | 'ended';
}

const EmergencyResponse: React.FC = () => {
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [form] = Form.useForm();
  const [selectedRows, setSelectedRows] = useState<DataType[]>([]);
  const [loading, setLoading] = useState(false);
  const [searchForm] = Form.useForm();

  // 获取等级对应的颜色
  const getLevelColor = (level: string) => {
    const colors = {
      'I': 'red',
      'II': 'orange',
      'III': 'yellow',
      'IV': 'blue'
    };
    return colors[level as keyof typeof colors] || 'default';
  };

  const columns: ColumnsType<DataType> = [
    {
      title: '序号',
      dataIndex: 'sequence',
      width: 80,
      fixed: 'left',
    },
    {
      title: '等级',
      dataIndex: 'level',
      width: 100,
      render: (level) => (
        <Tag color={getLevelColor(level)}>{level}级</Tag>
      ),
      filters: [
        { text: 'I级', value: 'I' },
        { text: 'II级', value: 'II' },
        { text: 'III级', value: 'III' },
        { text: 'IV级', value: 'IV' },
      ],
    },
    {
      title: '响应名称',
      dataIndex: 'responseName',
      ellipsis: true,
      sorter: (a, b) => a.responseName.localeCompare(b.responseName),
    },
    {
      title: '响应内容',
      dataIndex: 'responseContent',
      ellipsis: true,
    },
    {
      title: '状态',
      dataIndex: 'status',
      width: 100,
      render: (status) => (
        <Tag color={status === 'active' ? 'green' : 'gray'}>
          {status === 'active' ? '进行中' : '已结束'}
        </Tag>
      ),
    },
    {
      title: '时间',
      dataIndex: 'time',
      width: 120,
      sorter: (a, b) => new Date(a.time).getTime() - new Date(b.time).getTime(),
    },
    {
      title: '启动人',
      dataIndex: 'initiator',
      width: 100,
    },
    {
      title: '操作',
      key: 'actions',
      width: 200,
      fixed: 'right',
      render: (_, record) => (
        <Space>
          <a style={{ color: '#4169E1' }}>查看</a>
          {record.status === 'active' && (
            <Popconfirm
              title="确定要结束此响应吗？"
              onConfirm={() => handleEndResponse(record.key)}
            >
              <a>结束响应</a>
            </Popconfirm>
          )}
          <Popconfirm
            title="确定要删除吗？"
            onConfirm={() => handleDelete(record.key)}
          >
            <a style={{ color: '#FF0000' }}>删除</a>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  // 模拟数据
  const data: DataType[] = Array(13).fill(null).map((_, index) => ({
    key: index + 1,
    sequence: index + 1,
    level: 'IV',
    responseName: '针对"某某"台风启动V级响应',
    responseContent: '请各单位做好......',
    time: '2022-03-04',
    initiator: '小龙',
    status: index % 2 === 0 ? 'active' : 'ended',
  }));

  // 处理函数
  const handleAdd = () => {
    setIsModalVisible(true);
  };

  const handleEndResponse = (key: number) => {
    message.success('响应已结束');
  };

  const handleDelete = (key: number) => {
    message.success('删除成功');
  };

  const handleExport = () => {
    message.success('导出成功');
  };

  const handleImport = () => {
    message.success('导入成功');
  };

  const handleModalOk = async () => {
    try {
      const values = await form.validateFields();
      console.log('Success:', values);
      setIsModalVisible(false);
      form.resetFields();
      message.success('添加成功');
    } catch (errorInfo) {
      console.log('Failed:', errorInfo);
    }
  };

  return (
    <div className='container'>
      <Form
        form={searchForm}
        layout="inline"
        className='searchBar'
      >
        <div className='searchItems'>
          <Form.Item name="dateRange" label="时间">
            <RangePicker style={{ width: '240px' }} />
          </Form.Item>
          
          <Form.Item name="level" label="等级">
            <Select
              placeholder="请选择"
              style={{ width: '200px' }}
              options={[
                { value: 'IV', label: 'IV级' },
                { value: 'III', label: 'III级' },
                { value: 'II', label: 'II级' },
                { value: 'I', label: 'I级' },
              ]}
            />
          </Form.Item>

          <Form.Item name="keyword" label="关键词">
            <Input placeholder="请输入关键词" style={{ width: '200px' }} />
          </Form.Item>
          
          <Button type="primary" icon={<SearchOutlined />}>查询</Button>
          <Button icon={<ReloadOutlined />}>重置</Button>
        </div>
        
        <Space>
          <Button type="primary" icon={<PlusOutlined />} onClick={handleAdd}>
            新增响应
          </Button>
          <Button icon={<ExportOutlined />} onClick={handleExport}>
            导出
          </Button>
          <Button icon={<ImportOutlined />} onClick={handleImport}>
            导入
          </Button>
        </Space>
      </Form>

      <Table 
        columns={columns} 
        dataSource={data}
        loading={loading}
        scroll={{ x: 1300 }}
        rowSelection={{
          onChange: (_, selectedRows) => {
            setSelectedRows(selectedRows);
          }
        }}
        pagination={{
          total: 50,
          pageSize: 10,
          showQuickJumper: true,
          showSizeChanger: true,
          showTotal: (total) => `共 ${total} 条`,
        }}
      />

      <Modal
        title="新增应急响应"
        visible={isModalVisible}
        onOk={handleModalOk}
        onCancel={() => {
          setIsModalVisible(false);
          form.resetFields();
        }}
        width={600}
      >
        <Form
          form={form}
          layout="vertical"
        >
          <Form.Item
            name="level"
            label="响应等级"
            rules={[{ required: true, message: '请选择响应等级' }]}
          >
            <Select
              options={[
                { value: 'IV', label: 'IV级' },
                { value: 'III', label: 'III级' },
                { value: 'II', label: 'II级' },
                { value: 'I', label: 'I级' },
              ]}
            />
          </Form.Item>

          <Form.Item
            name="responseName"
            label="响应名称"
            rules={[{ required: true, message: '请输入响应名称' }]}
          >
            <Input />
          </Form.Item>

          <Form.Item
            name="responseContent"
            label="响应内容"
            rules={[{ required: true, message: '请输入响应内容' }]}
          >
            <TextArea rows={4} />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default EmergencyResponse;
